package ca.etsmtl.log430.lab3;

import java.io.*;

public class SplitFilter extends Thread {

	// Declarations

	boolean done;

	PipedReader inputPipe = new PipedReader();
	PipedWriter outputPipe1 = new PipedWriter();
	PipedWriter outputPipe2 = new PipedWriter();

	public SplitFilter(PipedWriter inputPipe, PipedWriter outputPipe1, PipedWriter outputPipe2) {

		try {

			// Connect inputPipe
			this.inputPipe.connect(inputPipe);
			System.out.println("SplitFilter:: connected to upstream filter.");

			// Connect OutputPipes

			this.outputPipe1 = outputPipe1;
			this.outputPipe2 = outputPipe2;
			System.out.println("SplitFilter:: connected to downstream filters.");

		} catch (Exception Error) {

			System.out.println("SplitFilter:: Error connecting to other filters.");

		} // try/catch

	} // Constructor

	// This is the method that is called when the thread is started

	public void run() {

		// Declarations

		char[] characterValue = new char[1];
		// char array is required to turn char into a string
		// string is required to look for the status code
		int integerCharacter; // the integer value read from the pipe

		try {

			done = false;

			while (!done) {

				integerCharacter = inputPipe.read();
				characterValue[0] = (char) integerCharacter;

				if (integerCharacter == -1) { // pipe is closed

					done = true;

				} else {
					outputPipe1.write(integerCharacter);
					outputPipe2.write(integerCharacter);

				} // if

			} // while

		} catch (Exception error) {

			System.out.println("SplitFilter:: Interrupted.");

		} // try/catch

		try {

			inputPipe.close();
			System.out.println("SplitFilter:: input pipe closed.");

			outputPipe1.close();
			outputPipe2.close();
			System.out.println("SplitFilter:: output pipes closed.");

		} catch (Exception Error) {

			System.out.println("SplitFilter:: Error closing pipes.");

		} // try/catch

	} // run

} // class